"""
API调试端点
提供用于调试目的的API端点，例如验证认证状态、检查token等
"""
from flask import Blueprint, jsonify, request, current_app, g
from app.utils.auth import auth_required, JWT_BYPASS_ENABLED
from datetime import datetime
import jwt
import platform
import time
import os

# 创建蓝图
debug_bp = Blueprint('debug', __name__, url_prefix='/api/debug')

@debug_bp.route('/auth-status', methods=['GET'])
def auth_status():
    """检查认证状态（无需认证）"""
    auth_header = request.headers.get('Authorization')
    result = {
        'timestamp': datetime.utcnow().isoformat(),
        'has_auth_header': auth_header is not None,
        'auth_header_format': None,
        'token_format': None,
        'token_valid': False,
        'token_details': None,
        'error': None
    }
    
    if auth_header:
        result['auth_header_format'] = 'Valid' if auth_header.startswith('Bearer ') else 'Invalid'
        
        try:
            if auth_header.startswith('Bearer '):
                token = auth_header.split(' ')[1]
                result['token_format'] = 'Valid format'
                
                # 尝试解析但不验证token
                decoded = jwt.decode(
                    token, 
                    options={"verify_signature": False}
                )
                
                result['token_details'] = {
                    'sub': decoded.get('sub'),
                    'exp': decoded.get('exp'),
                    'expires_at': datetime.fromtimestamp(decoded.get('exp')).isoformat() if decoded.get('exp') else None,
                    'expired': decoded.get('exp') and datetime.utcnow().timestamp() > decoded.get('exp')
                }
                
                # 尝试验证token
                try:
                    payload = jwt.decode(
                        token,
                        current_app.config['SECRET_KEY'],
                        algorithms=["HS256"]
                    )
                    result['token_valid'] = True
                except jwt.ExpiredSignatureError:
                    result['error'] = 'Token已过期'
                except jwt.InvalidTokenError:
                    result['error'] = '无效的Token签名'
                except Exception as e:
                    result['error'] = f'验证过程错误: {str(e)}'
                    
            else:
                result['token_format'] = 'Missing Bearer prefix'
                
        except Exception as e:
            result['error'] = f'Token解析错误: {str(e)}'
    
    return jsonify({
        'code': 200,
        'message': 'Auth status check',
        'data': result
    })

@debug_bp.route('/verify-auth', methods=['GET'])
@auth_required
def verify_auth():
    """检查认证是否有效（需要认证）"""
    return jsonify({
        'code': 200,
        'message': '认证有效',
        'data': {
            'user_id': g.user_id,
            'timestamp': datetime.utcnow().isoformat()
        }
    })

@debug_bp.route('/server-info', methods=['GET'])
def server_info():
    """获取服务器基本信息（无需认证）"""
    
    return jsonify({
        'code': 200,
        'message': '服务器信息',
        'data': {
            'server': platform.node(),
            'os': platform.platform(),
            'python': platform.python_version(),
            'time': time.strftime('%Y-%m-%d %H:%M:%S'),
            'uptime': time.time(),  # 实际应用中可以计算真正的启动时间
            'version': '1.0.0',  # 设置版本号
            'api_status': 'online'
        }
    })

@debug_bp.route('/auth-test', methods=['GET'])
def auth_test():
    """测试API连接和认证状态（无需认证）"""
    return jsonify({
        "code": 200,
        "message": "API连接正常",
        "data": {
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "bypass_enabled": JWT_BYPASS_ENABLED,
            "server": platform.node()
        }
    })

@debug_bp.route('/bypass-test', methods=['GET'])
@auth_required
def bypass_test():
    """测试认证绕过功能（需要认证但会被绕过）"""
    return jsonify({
        "code": 200,
        "message": "认证绕过测试成功",
        "data": {
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "bypass_enabled": JWT_BYPASS_ENABLED,
            "user_id": g.user_id,
            "server": platform.node()
        }
    })
